#!/usr/bin/env python
# -*- coding:utf-8 -*-

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
    #创建用户都是基于AbstractBaseUser，用户管理是继承BaseUserManager
)
import django

#此自定义用户代码都是引用Django官方代码修改而成

class UserProfileManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        """
        Creates and saves a User with the given email, name and password.
        """
        '''email是唯一标识，没有会报错'''
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=self.normalize_email(email),
            name=name,
        )

        user.set_password(password) #创建密码，加盐，hash等，并检测密码合理性
        user.save(using=self._db)   #保存密码到一个字典中
        return user

    def create_superuser(self, email, name, password):
        """
        创建超级用户的时候的字段
        """
        user = self.create_user(email,
            password=password,
            name=name
        )
        user.is_admin = True    #比创建用户多的一个字段
        user.save(using=self._db)
        return user #返回用户的实例


class UserProfile(AbstractBaseUser):
    #按照往常一样，创建用户的字段
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    name = models.CharField(max_length=32)
    token = models.CharField(u'token', max_length=128,default=None,blank=True,null=True)
    department = models.CharField(u'部门', max_length=32,default=None,blank=True,null=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    tel = models.CharField(u'座机', max_length=32,default=None,blank=True,null=True)
    mobile = models.CharField(u'手机', max_length=32,default=None,blank=True,null=True)
    #business_unit = models.ManyToManyField(BusinessUnit)
    memo = models.TextField(u'备注', blank=True,null=True,default=None)
    # date_joined = models.DateTimeField(blank=True, auto_now_add=True)
    #valid_begin = models.DateTimeField(blank=True, auto_now=True)
    valid_begin_time = models.DateTimeField(default=django.utils.timezone.now)
    # valid_end_time = models.DateTimeField(blank=True,null=True,default=None)

    objects = UserProfileManager()    #创建用户
    #将两个类关联起来，其它地方会调用objects.create_user()方法

    USERNAME_FIELD = 'email'    #让这个字段当做用户名
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    '''django自带后台权限控制，对哪些表有查看权限等'''
    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    '''用户是否有权限看到app'''
    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin